package com.hunan.yllxy.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hunan.yllxy.exceptions.CustomerException;
import com.hunan.yllxy.repostitory.dao.*;
import com.hunan.yllxy.repostitory.entity.*;
import com.hunan.yllxy.util.*;
import com.hunan.yllxy.vo.PageQuery;
import com.hunan.yllxy.vo.StatisticsVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @Author: 刘华
 * @Date: 2025/6/16 下午8:42
 * @Version 1.0
 */
@Service
@Slf4j
public class MainService {
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private UserRoleDao userRoleDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private ExcelUtils excelUtils;
    @Autowired
    private ActivityInfoDao activityInfoDao;
    @Autowired
    private PowerStationDao powerStationDao;
    @Autowired
    private MaterialsStationDao materialsStationDao;
    @Autowired
    private DakaScoreInfoDao dakaScoreInfoDao;
    @Autowired
    private DakaContentInfoDao dakaContentInfoDao;
    @Autowired
    private DakaOptionInfoDao dakaOptionInfoDao;
    @Autowired
    private UserDakaInfoDao userDakaInfoDao;
    @Autowired
    private MinioUtil minioUtil;

    public void testApp1() {

        log.info("testApp1");
    }

    public void addSimpleUser(UserInfo userInfo) {
        userInfo.check();
        UserInfo byAccount = userInfoDao.findByAccount(userInfo.getAccount());
        if (StringUtils.isNotNull(userInfo.getId())) {
            if (byAccount != null && !byAccount.getId().equals(userInfo.getId())) {
                throw new RuntimeException("用户已存在");
            }
        } else if (byAccount != null) {
            throw new RuntimeException("用户已存在");
        }
        if (userInfo.getId() == null) {
            String encode = passwordEncoder.encode("123456");
            userInfo.setPassword(encode);
            userInfoDao.save(userInfo);
            UserRole userRole = new UserRole();
            userRole.setRoleId("1");
            userRole.setUserId(userInfo.getId());
            userRoleDao.save(userRole);
        } else {
            userInfoDao.updateById(userInfo);
        }
    }

    public void updateUser(UserInfo userInfo) {
        userInfo.check();
        UserInfo byAccount = userInfoDao.findByAccount(userInfo.getAccount());
        if (byAccount != null && !byAccount.getId().equals(userInfo.getId())) {
            throw new RuntimeException("用户已存在");
        }
        userInfoDao.updateById(userInfo);

    }

    public void addAdminUser(UserInfo userInfo) {
        userInfo.check();
        UserInfo byAccount = userInfoDao.findByAccount(userInfo.getAccount());
        if (StringUtils.isNotNull(userInfo.getId())) {
            if (byAccount != null && !byAccount.getId().equals(userInfo.getId())) {
                throw new RuntimeException("用户已存在");
            }
        } else if (byAccount != null) {
            throw new RuntimeException("用户已存在");
        }
        if (userInfo.getId() == null) {
            String encode = passwordEncoder.encode("123456");
            userInfo.setPassword(encode);
            userInfoDao.save(userInfo);
            UserRole userRole = new UserRole();
            userRole.setRoleId("2");
            userRole.setUserId(userInfo.getId());
            userRoleDao.save(userRole);
            userRole = new UserRole();
            userRole.setRoleId("1");
            userRole.setUserId(userInfo.getId());
            userRoleDao.save(userRole);
        } else {
            userInfoDao.updateById(userInfo);
        }
    }

    public void exportUser(HttpServletResponse response) {
        List<UserInfo> userInfos = userInfoDao.findByRole("1");
        try {
            excelUtils.exportExcel(userInfos, "用户", "用户", UserInfo.class, "用户", response);
        } catch (IOException e) {
            log.info("导出用户失败");
            throw new RuntimeException(e);
        }
    }

    public ResponseEntity addActivityData(ActivityInfo activityInfo) {
        activityInfo.check();
        activityInfo.setUpdateTime(new Date());
        activityInfoDao.saveOrUpdate(activityInfo);

        return ResponseEntity.ok(null);
    }

    public ResponseEntity queryActivity() {
        List<ActivityInfo> list = activityInfoDao.myList();

        return ResponseEntity.ok(list);
    }

    public ResponseEntity deleteActivity(String activityId) {
        activityInfoDao.removeById(activityId);

        return ResponseEntity.ok(null);
    }

    public ResponseEntity lastActivity() {
        ActivityInfo activityInfo = activityInfoDao.lastActivity();

        return ResponseEntity.ok(activityInfo);
    }

    public ResponseEntity addOrUpdatePowerStation(PowerStation powerStation) {
        powerStation.setUpdateTime(new Date());
        powerStationDao.saveOrUpdate(powerStation);
        return ResponseEntity.ok(null);
    }

    public ResponseEntity powerStationQuery(PageQuery pageQuery) {
        Page<PowerStation> page = powerStationDao.powerStationQuery(pageQuery);

        return ResponseEntity.ok(page);
    }

    public ResponseEntity deletePowerStation(String powerStationId) {
        powerStationDao.removeById(powerStationId);
        return ResponseEntity.ok(null);
    }

    public ResponseEntity addOrUpdateMaterialsStation(MaterialsStation materialsStation) {
        materialsStation.setUpdateTime(new Date());
        if (materialsStation.getId() == null) {
            if (materialsStation.getSortIndex() == null) {
                Integer sortIndex = materialsStationDao.lastMaterialsStation();
                materialsStation.setSortIndex(sortIndex);
            }
        }
        materialsStationDao.saveOrUpdate(materialsStation);
        return ResponseEntity.ok(null);
    }

    public ResponseEntity importMaterialsStation(MultipartFile multipartFile) {
        File file = null;
        try {
            String tempDir = TempPathUtil.getTempPath();
            file = new File(tempDir);
            String originalFilename = multipartFile.getOriginalFilename();
            File zipFile = new File(tempDir + File.separator + originalFilename);
            zipFile.createNewFile();
            FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), zipFile);
            ZipUtils.unZipFiles(zipFile, tempDir);
            HashMap<String, File> fileHashMap = ZipUtils.getMapFile(file);
            for (String fileName : fileHashMap.keySet()) {
                MaterialsStation materialsStation = new MaterialsStation();
                materialsStation.setUpdateTime(new Date());
                try {
                    int parseInt = Integer.parseInt(fileName);
                    materialsStation.setSortIndex(parseInt);
                } catch (Exception e) {
                    Integer i = materialsStationDao.lastMaterialsStation();
                    materialsStation.setSortIndex(i);
                }

                materialsStation.setUpdateTime(new Date());

                materialsStation.setFileName(fileName);
                materialsStation.setTitleName(fileName);
                materialsStation.setDesText(fileName);
                materialsStation.setBucketName("yllxy");
                materialsStation.setPublishState(1);
                File dataFile = fileHashMap.get(fileName);
                String minioFileName = minioUtil.putObject("yllxy", dataFile);
                materialsStation.setMinioFile(minioFileName);
                materialsStationDao.save(materialsStation);
            }
        } catch (Exception e) {
            throw new CustomerException("导入失败！");
        } finally {
            try {
                FileUtils.deleteDirectory(file);
            } catch (IOException e) {
                log.error("删除文件失败");
            }
        }
        return ResponseEntity.ok(null);

    }

    public ResponseEntity deleteMaterialsStation(String materialsStationId) {
        materialsStationDao.removeById(materialsStationId);
        return ResponseEntity.ok(null);
    }

    public ResponseEntity materialsStationQuery() {
        LambdaQueryWrapper<MaterialsStation> wrapper = Wrappers.lambdaQuery(MaterialsStation.class).orderByAsc(MaterialsStation::getSortIndex);
        List<MaterialsStation> list = materialsStationDao.list(wrapper);
        return ResponseEntity.ok(list);
    }

    public ResponseEntity addOrUpdateScore(DakaScoreInfo dakaScoreInfo) {
        dakaScoreInfo.setUpdateTime(new Date());
        dakaScoreInfoDao.saveOrUpdate(dakaScoreInfo);
        return ResponseEntity.ok(null);
    }

    public ResponseEntity queryScore(String activityId) {
        List<DakaScoreInfo> dakaScoreInfoList = dakaScoreInfoDao.findByActivityId(activityId);
        return ResponseEntity.ok(dakaScoreInfoList);
    }

    public ResponseEntity deleteScore(String id) {
        dakaScoreInfoDao.removeById(id);
        return ResponseEntity.ok(null);
    }

    public ResponseEntity addContent(DakaContentInfo dakaContentInfo) {
        dakaContentInfo.check();
        dakaContentInfoDao.saveOrUpdate(dakaContentInfo);
        return ResponseEntity.ok(null);
    }

    public ResponseEntity deleteContent(String id) {
        dakaContentInfoDao.removeById(id);

        return ResponseEntity.ok(null);
    }

    public ResponseEntity queryContent(String activityId) {
        List<DakaContentInfo> contentInfos = dakaContentInfoDao.findByActivityId(activityId);

        return ResponseEntity.ok(contentInfos);
    }

    public ResponseEntity userQueryContent(String activityId) {
        return null;
    }

    public ResponseEntity addOption(DakaOptionInfo dakaOptionInfo) {
        dakaOptionInfoDao.saveOrUpdate(dakaOptionInfo);
        return ResponseEntity.ok(null);
    }

    public ResponseEntity queryOption(String contentId) {
        List<DakaOptionInfo> dakaContentInfos = dakaOptionInfoDao.findByContentId(contentId);
        return ResponseEntity.ok(dakaContentInfos);
    }

    public ResponseEntity deleteOption(String id) {
        dakaOptionInfoDao.removeById(id);
        return ResponseEntity.ok(null);

    }

    public ResponseEntity dakaContent(String activityId) {
        UserInfo nowUser = SecurityUtils.getNowUser();
        DakaContentInfo dakaContentInfo = dakaContentInfoDao.dakaContent(activityId, nowUser.getId());
        if (dakaContentInfo != null) {
            List<DakaOptionInfo> optionInfoList = dakaOptionInfoDao.findByContentId(dakaContentInfo.getId());
            dakaContentInfo.setDakaOptionInfos(optionInfoList);
        }
        return ResponseEntity.ok(dakaContentInfo);
    }

    public ResponseEntity daka(UserDakaInfo userDakaInfo) {
//        UserDakaInfo query = userDakaInfoDao.findByContentId(userDakaInfo.getUserId(), userDakaInfo.getDakaContentId());
//        if (query != null) {
//            throw new CustomerException("已打卡");
//        }
        userDakaInfo.check();
        String dakaContentId = userDakaInfo.getDakaContentId();
        DakaContentInfo contentInfo = dakaContentInfoDao.getById(dakaContentId);
        if (contentInfo == null) {
            throw new CustomerException("打卡不存在");
        }
        Date deadline = contentInfo.getDeadline();
        if (DateUtils.dateAddAndSubtract(new Date(), deadline)) {
            throw new CustomerException("打卡已截止");
        }
        UserInfo nowUser = SecurityUtils.getNowUser();
        userDakaInfo.setUserId(nowUser.getId());
        userDakaInfo.setUpdateTime(new Date());
        userDakaInfoDao.saveOrUpdate(userDakaInfo);
        return ResponseEntity.ok(null);
    }

    public ResponseEntity powerStationQueryPublish(PageQuery pageQuery) {
        Page<PowerStation> page = powerStationDao.powerStationQueryPublish(pageQuery);
        return ResponseEntity.ok(page);
    }

    public ResponseEntity dakaRecord(String activityId) {
        UserInfo nowUser = SecurityUtils.getNowUser();
        List<DakaContentInfo> dakaContentInfos = dakaContentInfoDao.dakaRecord(nowUser.getId(), activityId);

        return ResponseEntity.ok(dakaContentInfos);
    }

    public ResponseEntity userDakaRecord(String activityId, PageQuery pageQuery) {
        Page<UserInfo> page = PageResultUtils.getPage(pageQuery, UserInfo.class);
        page = userInfoDao.findByRolePageQuery("1", page);
        List<UserInfo> records = page.getRecords();
        for (UserInfo record : records) {
            List<DakaContentInfo> dakaContentInfos = dakaContentInfoDao.dakaRecord(record.getId(), activityId);
            record.setDakaContentInfos(dakaContentInfos);
        }
        return ResponseEntity.ok(page);
    }

    public ResponseEntity histogram(String activityId) {
        Date date = new Date();
        UserInfo nowUser = SecurityUtils.getNowUser();
        ArrayList<StatisticsVo> statisticsVos = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            List<UserDakaInfo> dakaInfoList = userDakaInfoDao.findByActivityIdAndDate(nowUser.getId(), activityId, date);
            if (dakaInfoList == null) {
                dakaInfoList = new ArrayList<>();
            }
            statisticsVos.add(new StatisticsVo(DateUtils.getStringDate(date, DateUtils.FORMAT1), dakaInfoList.size()));
            date = DateUtils.addDateDay(date, -1);
        }
        return ResponseEntity.ok(statisticsVos);
    }
    public ResponseEntity brokenLineGraph2(String activityId, String contentId) {
        UserInfo nowUser = SecurityUtils.getNowUser();
        ArrayList<StatisticsVo> statisticsVos = new ArrayList<>();

        List<UserDakaInfo> userDakaInfoList = userDakaInfoDao.findByContentIdList(nowUser.getId(), contentId);
        Integer index=1;
        for (UserDakaInfo userDakaInfo : userDakaInfoList) {
            String dakaScoreId = userDakaInfo.getDakaScoreId();
            DakaScoreInfo scoreInfo = dakaScoreInfoDao.getById(dakaScoreId);
            Integer score = null;
            if (scoreInfo != null) {
                score = scoreInfo.getDakaScore();
            }
            if (score == null) {
                break;
            }
            statisticsVos.add(new StatisticsVo("第"+index+"次", score));
            index++;
        }
        return ResponseEntity.ok(statisticsVos);
    }
    public ResponseEntity brokenLineGraph(String activityId) {
        List<DakaContentInfo> infoList = dakaContentInfoDao.findByActivityId(activityId);
        ArrayList<StatisticsVo> statisticsVos = new ArrayList<>();
        UserInfo nowUser = SecurityUtils.getNowUser();
        for (DakaContentInfo dakaContentInfo : infoList) {
            UserDakaInfo dakaInfo = userDakaInfoDao.findByContentId(nowUser.getId(), dakaContentInfo.getId());
            Integer score = null;
            if (dakaInfo != null) {
                String dakaScoreId = dakaInfo.getDakaScoreId();
                DakaScoreInfo scoreInfo = dakaScoreInfoDao.getById(dakaScoreId);
                if (scoreInfo != null) {
                    score = scoreInfo.getDakaScore();
                }
            }
            if (score == null) {
                break;
            }
            statisticsVos.add(new StatisticsVo(dakaContentInfo.getTitleName(), score));

        }
        return ResponseEntity.ok(statisticsVos);
    }

    public ResponseEntity userList(PageQuery pageQuery, String roleId) {
        Page<UserInfo> page = PageResultUtils.getPage(pageQuery, UserInfo.class);

        page = userInfoDao.findByRolePageQuery(roleId, page);
        List<UserInfo> records = page.getRecords();
        for (UserInfo record : records) {
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            List<String> roleIds = userRoleDao.findByUserId(record.getId());
            if (StringUtils.isNotNull(records)) {
                List<Role> roles = roleDao.findByIds(roleIds);
                for (Role role : roles) {
                    String name = role.getName();
                    SimpleGrantedAuthority authority = new SimpleGrantedAuthority(name);
                    authorities.add(authority);
                }
            }
            record.setAuthorityList(authorities);
        }
        return ResponseEntity.ok(page);
    }

    public void deleteUser(String userId) {
        userInfoDao.removeById(userId);
    }


    public ResponseEntity queryUserRecord(PageQuery pageQuery, String userId, String activityId, String dakaContentId, String dakaOptionId) {
        Page<UserDakaInfo> userDakaInfoPage = userDakaInfoDao.queryUserRecord(pageQuery, userId, activityId,dakaContentId,dakaOptionId);
        return ResponseEntity.ok(userDakaInfoPage);
    }

    public void exportQueryUserRecord(String userId, String activityId, String dakaContentId, HttpServletResponse response, String dakaOptionId) {
        List<UserDakaInfo> userDakaInfos = userDakaInfoDao.queryUserRecordList(userId, activityId,dakaContentId,dakaOptionId);
        try {
            excelUtils.exportExcel(userDakaInfos, "用户打卡记录", "用户打卡记录", UserDakaInfo.class, "用户", response);
        } catch (IOException e) {
            log.info("导出用户失败");
            throw new RuntimeException(e);
        }
    }



}
